<template>
  <ElDialog
    :model-value="visible"
    :title="title"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      @keyup.enter="handleSubmit"
    >
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="商户" prop="merchantId">
            <ElSelect
              v-model="formData.merchantId"
              placeholder="请选择商户"
              filterable
              remote
              :remote-method="searchMerchants"
              :loading="merchantLoading"
              style="width: 100%"
              @change="handleMerchantChange"
            >
              <ElOption
                v-for="merchant in merchantOptions"
                :key="merchant.id"
                :label="`${merchant.merchantName} (${merchant.merchantCode})`"
                :value="merchant.id"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="当前余额" prop="currentBalance">
            <ElInputNumber
              v-model="formData.currentBalance"
              :precision="2"
              :step="0.01"
              placeholder="当前余额"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="信用额度" prop="creditLimit">
            <ElInputNumber
              v-model="formData.creditLimit"
              :precision="2"
              :step="0.01"
              :min="0"
              placeholder="信用额度"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="状态" prop="status">
            <ElRadioGroup v-model="formData.status">
              <ElRadio :value="1">正常</ElRadio>
              <ElRadio :value="0">冻结</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="备注" prop="remark">
            <ElInput
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="200"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <ElButton @click="handleClose">取消</ElButton>
      <ElButton type="primary" :loading="submitting" @click="handleSubmit">
        确定
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from "vue";
import { WmsMerchantService } from "@/api/wms/basicApi";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({ name: "WmsMerchantBalanceDialog" });

// Props
interface Props {
  visible: boolean;
  type: "add" | "edit";
  balanceData?: WMS.Basic.MerchantBalanceInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  balanceData: null,
});

// Emits
const emit = defineEmits<{
  "update:visible": [visible: boolean];
  submit: [data: WMS.Basic.MerchantBalanceInfo];
}>();

// Form ref
const formRef = ref<FormInstance>();

// 提交状态
const submitting = ref(false);

// 商户选项相关
const merchantOptions = ref<WMS.Basic.MerchantInfo[]>([]);
const merchantLoading = ref(false);

// 弹窗标题
const title = computed(() => {
  return props.type === "edit" ? "编辑商户余额" : "新增商户余额";
});

// 表单数据
const formData = reactive<Partial<WMS.Basic.MerchantBalanceInfo>>({
  merchantId: undefined,
  merchantName: "",
  merchantCode: "",
  currentBalance: 0,
  creditLimit: 0,
  status: 1,
  remark: "",
});

// 表单验证规则
const rules: FormRules = {
  merchantId: [{ required: true, message: "请选择商户", trigger: "change" }],
  currentBalance: [
    { required: true, message: "请输入当前余额", trigger: "blur" },
    { type: "number", message: "余额必须是数字", trigger: "blur" },
  ],
  creditLimit: [
    { type: "number", min: 0, message: "信用额度不能小于0", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 监听数据变化，初始化表单
watch(
  () => [props.visible, props.balanceData],
  () => {
    if (props.visible) {
      resetForm();
      if (props.type === "edit" && props.balanceData) {
        Object.assign(formData, {
          id: props.balanceData.id,
          merchantId: props.balanceData.merchantId,
          merchantName: props.balanceData.merchantName,
          merchantCode: props.balanceData.merchantCode,
          currentBalance: props.balanceData.currentBalance,
          creditLimit: props.balanceData.creditLimit || 0,
          status: props.balanceData.status,
          remark: props.balanceData.remark || "",
        });

        // 如果是编辑模式，添加当前商户到选项列表
        if (props.balanceData.merchantId) {
          merchantOptions.value = [
            {
              id: props.balanceData.merchantId,
              merchantName: props.balanceData.merchantName || "",
              merchantCode: props.balanceData.merchantCode || "",
            } as WMS.Basic.MerchantInfo,
          ];
        }
      }
    }
  },
  { immediate: true },
);

// 重置表单
const resetForm = () => {
  formData.merchantId = undefined;
  formData.merchantName = "";
  formData.merchantCode = "";
  formData.currentBalance = 0;
  formData.creditLimit = 0;
  formData.status = 1;
  formData.remark = "";
  merchantOptions.value = [];
  formRef.value?.clearValidate();
};

// 搜索商户
const searchMerchants = async (query: string) => {
  if (!query) {
    merchantOptions.value = [];
    return;
  }

  try {
    merchantLoading.value = true;
    const response = await WmsMerchantService.getMerchantList({
      merchantName: query,
      current: 1,
      size: 20,
    });
    merchantOptions.value = response.data?.rows || [];
  } catch (error) {
    console.error("Error searching merchants:", error);
    ElMessage.error("搜索商户失败");
  } finally {
    merchantLoading.value = false;
  }
};

// 商户选择变化处理
const handleMerchantChange = (merchantId: number) => {
  const selectedMerchant = merchantOptions.value.find(
    (m) => m.id === merchantId,
  );
  if (selectedMerchant) {
    formData.merchantName = selectedMerchant.merchantName;
    formData.merchantCode = selectedMerchant.merchantCode;
  }
};

// 关闭弹窗
const handleClose = () => {
  emit("update:visible", false);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const submitData = { ...formData } as WMS.Basic.MerchantBalanceInfo;
    emit("submit", submitData);
  } catch (error) {
    console.error("Form validation failed:", error);
  } finally {
    submitting.value = false;
  }
};

// 页面加载时获取商户列表
onMounted(async () => {
  if (props.type === "add") {
    try {
      const response = await WmsMerchantService.getAllMerchants();
      merchantOptions.value = response.data || [];
    } catch (error) {
      console.error("Error loading merchants:", error);
    }
  }
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
